package com.sptpc.demo1.service.impl;

import com.sptpc.demo1.model.Drink;
import com.sptpc.demo1.model.Order;
import com.sptpc.demo1.repository.DrinkRepository;
import com.sptpc.demo1.repository.OrderRepository;
import com.sptpc.demo1.service.IOrderService;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List;

@Service
public class OrderService implements IOrderService {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private DrinkRepository drinkRepository;
    @Override
    public void addOrder(Order order, List<Integer> items) {
        order.setState(0);
        List<Drink> drinks=drinkRepository.findAllById(items);
        order.setItems(drinks);
//        BigDecimal sum=BigDecimal.ZERO;//表示0
//        for (Drink drink : drinks) {
//            sum=sum.add(drink.getPrice().getAmount());
//        }

        BigDecimal sum=drinks.stream()
                .map(d -> d.getPrice().getAmount())
                .reduce(BigDecimal.ZERO,(p1,p2)->p1.add(p2));
        order.setPrice(Money.of(CurrencyUnit.of("CNY"),sum));
        orderRepository.save(order);
    }

    @Override
    public Order getIdOrder(Integer id) {
        return orderRepository.findById(id).orElse(null);
    }

    @Override
    public void updateOrder(Order order1) {
        orderRepository.save(order1);
    }

    @Override
    public void dleteOrder(Integer id) {
        orderRepository.deleteById(id);
    }

    @Override
    public List<Order> getOrderByCustomer(String customer) {
        Order order=new Order();
        order.setCustomer(customer);
        order.setState(0);
        Example<Order> example=Example.of(order);
        return orderRepository.findAll(example);
    }
}
